//
//  DRRRManager.m
//  Test-XMPP
//
//  Created by 秦 道平 on 14-3-28.
//  Copyright (c) 2014年 秦 道平. All rights reserved.
//
#import "DRRRMessage.h"
#import "DRRRRoster.h"
#import "DRRRManager.h"
#import "XMPP+DRRR.h"
#import "NSObject+additions.h"
#import "YYModel.h"
@implementation DRRRMessageContent
-(NSString*)talkid{
    return self.fromJid;
}
-(instancetype)initWithXMPPMessage:(XMPPMessage *)message{
    self=[super init];
    if (self){
        self.type=message.type;
        self.fromJid=[message.from bare];
        if ([self.type isEqualToString:@"chat"]){
            self.fromName=[message.from user];
        }
        else if ([self.type isEqualToString:@"groupchat"]){
            self.fromName=[message.from resource];
        }
        self.toJid=[message.to bare];
        self.toName=[message.to user];
        self.body=message.body;
        self.thread=message.thread;
        self.time=[NSDate date];
        self.messageid=message.attributesAsDictionary[@"id"];
        for (NSXMLElement* element in message.children) {
        
            if ([element.name isEqualToString:@"user"]){
                for (NSXMLElement* key in element.children) {
                    if ([key.name isEqualToString:@"name"]) {
                        self.name = [key.children.firstObject stringValue];
                    }else if ([key.name isEqualToString:@"headPath"]){
                        self.headPath = [key.children.firstObject stringValue];
                    }else if ([key.name isEqualToString:@"createTime"]){
                        self.createTime = [key.children.firstObject stringValue];
                    }else if ([key.name isEqualToString:@"sendDate"]){
                        self.sendDate = [key.children.firstObject stringValue];
                    }else if ([key.name isEqualToString:@"MESSAGE_TYPE"]){
                        self.MESSAGE_TYPE = [key.children.firstObject stringValue];
                    }else if ([key.name isEqualToString:@"IMAGE_URL"]){
                        self.IMAGE_URL = [key.children.firstObject stringValue];
                    }else if ([key.name isEqualToString:@"accountId"]){
                        self.accountId = [key.children.firstObject stringValue];
                    }else if ([key.name isEqualToString:@"partymemberId"]){
                        self.partymemberId = [key.children.firstObject stringValue];
                    }else if ([key.name isEqualToString:@"deptId"]){
                        self.deptId = [key.children.firstObject stringValue];
                    }
                }
                
                break;
            }
        }
        
    }
    
    return self;
}

-(NSString*)description{
    return [self yy_modelDescription];
}
-(BOOL)isChat{
    return [self.type isEqualToString:@"chat"];
}
-(BOOL)isGroupChat{
    return [self.type isEqualToString:@"groupchat"];
}
-(BOOL)mySender{
    if (self.isChat){
        return [self.fromJid isEqualToString:[DRRRManager sharedManager].jid];
    }
    else if (self.isGroupChat){
        return [self.fromName isEqualToString:[DRRRManager sharedManager].username];
    }
    return NO;
}
-(NSDate*)showTime{
    return self.delayTime?self.delayTime:self.time;
}

#pragma mark - cell高度
- (CGFloat)cellHeigth{
    CGFloat imageWidth = 38 * [UIScreen zj_screenWScale];
    CGFloat labelWith = [UIScreen zj_screenWith] - imageWidth - (30 + 10 + 10 + 10) * [UIScreen zj_screenWScale];

    CGFloat height = [self.body getLabelSizeWithLabelFont:[UIFont titleTextFont] labelWidth:labelWith labelNumberOfLines:0 labelLineSpace:4 * [UIScreen zj_screenHScale] labelCharacterSpace:1];
    
    CGFloat cellHigit = height + [NSString heightWithTextFont:[UIFont titleTextFont]] + (20 + 8 + 5) * [UIScreen zj_screenHScale];
    
    return cellHigit;
}

- (CGFloat)cell_bgImageView_width{
    CGFloat imageWidth = 38 * [UIScreen zj_screenWScale];
    CGFloat labelWith = [UIScreen zj_screenWith] - imageWidth - (30 + 10 + 10 + 10) * [UIScreen zj_screenWScale];
    
    CGSize labelSize = [self.body zj_getLabelSizeWithLabelFont:[UIFont titleTextFont] labelWidth:labelWith labelNumberOfLines:0 labelLineSpace:4 * [UIScreen zj_screenHScale] labelCharacterSpace:1];
    return labelSize.width + 30 * [UIScreen zj_screenWScale];
}

@end

@implementation DRRRMessage
static DRRRMessage* _sharedMessage;
+(DRRRMessage*)sharedMessage{
    if (!_sharedMessage){
        _sharedMessage=[[super allocWithZone:NULL]init];
        [_sharedMessage setupMessage];
    }
    return _sharedMessage;
}
-(void)setupMessage{
    _messageBundle=[[NSMutableDictionary alloc]init];
}

-(NSDictionary*)messageBundle{
    return _messageBundle;
}
#pragma mark - message
-(NSArray*)talksWithJid:(NSString *)jid{
    
    return _messageBundle[jid];
}
-(void)_receiveMessage:(DRRRMessageContent *)message{
    if (!message.talkid) {
        return;
    }
    NSString *lowerTalkid = [message.talkid lowercaseString];
    NSMutableArray* talks=_messageBundle[lowerTalkid];
    if (!talks){
        talks=[NSMutableArray array];
        _messageBundle[lowerTalkid]=talks;
    }
    
    NSInteger flag = 0;
    for (int i = 0; i < talks.count; i ++) {
        DRRRMessageContent *oldMessage = talks[i];
        if (([oldMessage.createTime isEqualToString: message.createTime] && [oldMessage.accountId isEqualToString: message.accountId])
            || [oldMessage.messageid isEqualToString: message.messageid] ) {
            flag = 1;
            break;
        }
    }
    
    if (flag == 0) {
        [talks addObject:message];
        
    }
    
    [[DRRRRoster sharedRoster] _increaseUnreadTotalForJid:message.talkid];
    [[NSNotificationCenter defaultCenter] postNotificationName:DRRRRefreshTalksNotification object:message];
}
-(DRRRMessageContent*)sendMessage:(NSString *)message
                            toJid:(NSString *)toJid
                           toName:(NSString *)toName{
    NSString* talkId=toJid;
    NSMutableArray* talks=_messageBundle[talkId];
    if (!talks){
        talks=[NSMutableArray array];
        _messageBundle[talkId]=talks;
    }
    DRRRMessageContent* content=[[DRRRMessageContent alloc]init];
    content.toJid=toJid;
    content.toName=toName;
    content.fromJid=[DRRRManager sharedManager].jid;
    content.fromName=[DRRRManager sharedManager].username;
    content.body=message;
    content.type=@"chat";
    content.time=[NSDate date];
    [talks addObject:content];
    
    ///更新对话列表的通知
    [[NSNotificationCenter defaultCenter] postNotificationName:DRRRRefreshTalksNotification object:content];
    ///发送xml
    //XMPPFramework主要是通过KissXML来生成XML文件
    //生成<body>文档
    NSXMLElement *body = [NSXMLElement elementWithName:@"body"];
    [body setStringValue:message];
    //生成XML消息文档
    NSXMLElement *mes = [NSXMLElement elementWithName:@"message"];
    //消息类型
    [mes addAttributeWithName:@"type" stringValue:@"chat"];
    //发送给谁
    [mes addAttributeWithName:@"to" stringValue:toJid];
    //由谁发送
    [mes addAttributeWithName:@"from" stringValue:[DRRRManager sharedManager].username];
    //组合
    [mes addChild:body];
    //发送消息
    [[DRRRManager sharedManager].xmppStream sendElement:mes];
    return content;
}
-(void)sendMessage:(NSString *)message inChatRoom:(NSString *)chatRoomJid{
    [self sendMessage:message inChatRoom:chatRoomJid isImageMessage:NO];
}
-(void)sendMessage:(NSString *)message inChatRoom:(NSString *)chatRoomJid isImageMessage:(BOOL)yesOrNO{
    NSString* talkId=chatRoomJid;
    NSMutableArray* talks=_messageBundle[talkId];
    if (!talks){
        talks=[NSMutableArray array];
        _messageBundle[talkId]=talks;
    }

    ///发送xml
    //XMPPFramework主要是通过KissXML来生成XML文件
    //生成<body>文档
    NSXMLElement *body = [NSXMLElement elementWithName:@"body"];
    [body setStringValue:message];
    //user文档
    NSXMLElement *user = [NSXMLElement elementWithName:@"user"];
    
    [user addAttributeWithName:@"xmlns" stringValue:@"com.dsfa.ipb"];
    //名字
    NSXMLElement *accountId = [NSXMLElement elementWithName:@"accountId"];
    [accountId setStringValue:[ZJUserInfoModel sharedUserInfo].ORG_ACCOUNT.ID];
    //名字
    NSXMLElement *partymemberId = [NSXMLElement elementWithName:@"partymemberId"];
    [partymemberId setStringValue:[ZJUserInfoModel sharedUserInfo].ORG_ACCOUNT.PARTY_MEMBER_ID];
    //名字
    NSXMLElement *deptId = [NSXMLElement elementWithName:@"deptId"];
    [deptId setStringValue:[ZJUserInfoModel sharedUserInfo].CURRENT_DEPT_MODEL.ID];
    //名字
    NSXMLElement *name = [NSXMLElement elementWithName:@"name"];
    [name setStringValue:[ZJUserInfoModel sharedUserInfo].ORG_ACCOUNT.USER_NAME];
    //发送时间
    NSXMLElement *sendDate = [NSXMLElement elementWithName:@"sendDate"];
    [sendDate setStringValue:[NSDateFormatter stringTimeWithDate:[NSDate date]]];
    
    //头像地址
    NSXMLElement *headPath = [NSXMLElement elementWithName:@"headPath"];
    [headPath setStringValue:[ZJUserInfoModel sharedUserInfo].ORG_ACCOUNT.PHOTO_URL];
    //创建时间
    NSXMLElement *createTime = [NSXMLElement elementWithName:@"createTime"];
    [createTime setStringValue:[NSDateFormatter stringTimeWithDate:[NSDate date]]];
    
    //消息类型
    NSXMLElement *MESSAGE_TYPE = [NSXMLElement elementWithName:@"MESSAGE_TYPE"];
    //图片地址
    NSXMLElement *IMAGE_URL = [NSXMLElement elementWithName:@"IMAGE_URL"];
    if (!yesOrNO) {//文字消息
        [MESSAGE_TYPE setStringValue:@"1"];
    }else{//图片消息
        [MESSAGE_TYPE setStringValue:@"2"];
        [IMAGE_URL setStringValue:message];
        [user addChild:IMAGE_URL];
    }
    
    [user addChild:name];
    [user addChild:sendDate];
    [user addChild:headPath];
    [user addChild:createTime];
    [user addChild:MESSAGE_TYPE];
    [user addChild:accountId];
    [user addChild:partymemberId];
    [user addChild:deptId];
    //生成XML消息文档
    NSXMLElement *mes = [NSXMLElement elementWithName:@"message"];
    //消息类型
    [mes addAttributeWithName:@"type" stringValue:@"groupchat"];
    //发送给谁
    [mes addAttributeWithName:@"to" stringValue:chatRoomJid];
    //由谁发送
    [mes addAttributeWithName:@"from" stringValue:[DRRRManager sharedManager].jid];
    //组合
    [mes addChild:body];
    [mes addChild:user];
    //发送消息
    [[DRRRManager sharedManager].xmppStream sendElement:mes];
}
#pragma mark - XMPPStreamDelegate
-(void)xmppStream:(XMPPStream *)sender didReceiveMessage:(XMPPMessage *)message{
    if (![message isChatRoomInvite] && !message.body){
        NSLog(@"body is empty");
        return;
    }
    DRRRMessageContent* content=[[DRRRMessageContent alloc]initWithXMPPMessage:message];
    NSString *string;
    if (content.isChat) {//单聊
        string = content.fromName;
//       [[DRRRManager sharedManager].keyValueStore createTableWithName:string];
        
    }
    if (content.isGroupChat) {//群聊
        
    }
    
    
    [self _receiveMessage:content];
}
-(void)xmppStream:(XMPPStream *)sender didReceivePresence:(XMPPPresence *)presence{
    
}
-(BOOL)xmppStream:(XMPPStream *)sender didReceiveIQ:(XMPPIQ *)iq{
    return YES;
}
@end
